package cn.xueden.common.core.context;

import cn.xueden.common.core.exception.BaseException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.rmi.server.ExportException;

public class RequestContextFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 将请求参数放入上下文
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        //做一次请求类型转换
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        RequestContext rc = new RequestContext();
        //对于请求参数的处理
        String companyCode = (String)request.getHeader("companyCode");
        //设置companyCode
        if(StringUtils.isBlank(companyCode)){
            throw  new BaseException("companyCode不能为空");
        }
        //设置companyId
        Long companyId = Long.valueOf(request.getHeader("companyId"));
        ContextHolder contextHolder = new ContextHolder();
        contextHolder.set(rc);
    }

}
